<template>
  <div class="category-page">
    <div class="container">
      <div class="category-header">
        <h1 class="category-title">{{ categoryName }}</h1>
        <div class="category-desc">{{ categoryDesc }}</div>
      </div>
      
      <!-- 文章列表 -->
      <div class="article-list" v-if="filteredArticles.length > 0">
        <div 
          v-for="article in filteredArticles" 
          :key="article.id" 
          class="article-item card" 
          @click="goToDetail(article.id)">
          <div class="article-main">
            <div class="article-info">
              <h3 class="article-title">{{ article.title }}</h3>
              <p class="article-summary">{{ article.summary }}</p>
              <div class="article-meta">
                <span class="author">
                  <el-avatar :size="20" :src="article.avatar || userAvatar"></el-avatar>
                  {{ article.nickName }}
                </span>
                <span><el-icon><Timer /></el-icon> {{ article.publishTime }}</span>
                <span><el-icon><View /></el-icon> {{ article.views }}</span>
                <span><el-icon><Star /></el-icon> {{ article.likes }}</span>
              </div>
            </div>
            <div class="article-cover" v-if="article.coverUrl">
              <img :src="article.coverUrl" :alt="article.title">
            </div>
          </div>
        </div>
      </div>
      
      <!-- 无数据 -->
      <div class="no-data" v-else>
        <el-empty description="暂无相关文章"></el-empty>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-section" v-if="filteredArticles.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 15, 20]"
          :total="totalArticles"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Timer, View, Star } from '@element-plus/icons-vue'
import request from '@/utils/request'
const route = useRoute()
const router = useRouter()

// 数据
const userAvatar = ref('https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png')
const categoryId = ref(parseInt(route.params.id))
const currentPage = ref(1)
const pageSize = ref(10)
const totalArticles = ref(0)
const articles = ref([])
const categories = ref([])
// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await request.get('/categories/list')
    
    if (res.data.code === '200') {
      categories.value = res.data.data || []
    } else {
      console.error('获取分类列表失败:', res.data.msg)

    }
  } catch (error) {
    console.error('获取分类列表出错:', error)
  }
}


// 计算属性
const category = computed(() => {
  return categories.value.find(item => item.id === categoryId.value) || {}
})

const categoryName = computed(() => {
  return category.value.name || '未知分类'
})

const categoryDesc = computed(() => {
  return category.value.description || '暂无描述'
})

const filteredArticles = computed(() => {
  return articles.value
})

// 监听器
watch(() => route.params.id, (newVal) => {
  categoryId.value = parseInt(newVal)
  currentPage.value = 1 // 切换分类时重置页码
  fetchCategoryArticles()
})

// 生命周期钩子
onMounted(() => {
  fetchCategories()
  fetchCategoryArticles()
})

// 方法
const fetchCategoryArticles = async () => {
  try {
    const res = await request.get('/articles/page', {
      params: {
        categoryId: categoryId.value,
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    
    if (res.data.code === '200') {
      articles.value = res.data.data.records || []
      totalArticles.value = res.data.data.total || 0
    } else {
      console.error('获取文章列表失败:', res.data.msg)
    }
  } catch (error) {
    console.error('获取文章列表出错:', error)
  }
}


const goToDetail = (id) => {
  router.push(`/detail/${id}`)
}

const handlePageChange = (page) => {
  currentPage.value = page
  fetchCategoryArticles()
  window.scrollTo(0, 0)
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1 // 切换每页条数时重置为第一页
  fetchCategoryArticles()
  window.scrollTo(0, 0)
}
 
</script>

<style scoped>
.category-page {
  padding: 20px 0 40px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}

.category-header {
  margin-bottom: 30px;
  text-align: center;
  padding: 30px 0;
  background-color: #f5f7fc;
  border-radius: 8px;
}

.category-title {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.category-desc {
  font-size: 16px;
  color: #666;
  max-width: 700px;
  margin: 0 auto;
  line-height: 1.6;
}

.card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  transition: all 0.3s;
  cursor: pointer;
}

.card:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.article-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 30px;
}

.article-item {
  padding: 15px;
}

.article-main {
  display: flex;
  gap: 20px;
}

.article-info {
  flex: 1;
}

.article-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.article-summary {
  color: #666;
  margin-bottom: 10px;
  line-height: 1.6;
}

.article-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  font-size: 13px;
  color: #999;
}

.article-meta > span {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 5px;
}

.article-meta .el-icon {
  margin-right: 5px;
}

.article-cover {
  width: 200px;
  height: 120px;
  overflow: hidden;
  border-radius: 4px;
}

.article-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.article-item:hover .article-cover img {
  transform: scale(1.05);
}

.author {
  display: flex;
  align-items: center;
  gap: 5px;
}

.category-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.category-tag {
  padding: 8px 16px;
  border-radius: 20px;
  background-color: #f4f4f5;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
}

.category-tag:hover {
  background-color: #e6f1fc;
  color: #409eff;
}

.category-tag.active {
  background-color: #409eff;
  color: #fff;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.no-data {
  padding: 40px 0;
}

@media screen and (max-width: 768px) {
  .article-main {
    flex-direction: column;
  }
  
  .article-cover {
    width: 100%;
    height: 180px;
    margin-top: 10px;
  }
  
  .filter-section {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-item {
    margin-right: 0;
    margin-bottom: 15px;
    width: 100%;
  }
}
</style> 